package com.cat.recruit.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;

@Configuration
@EnableCaching // 启用 Spring Cache
public class CacheConfig {

//    @Bean
//    public ObjectMapper objectMapper() {
//        ObjectMapper om = new ObjectMapper();
//        om.registerModule(new JavaTimeModule());
//        return om;
//    }

    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        // 配置键的序列化器（String 格式，避免乱码）
        StringRedisSerializer keySerializer = new StringRedisSerializer();

        // 配置值的序列化器（JSON 格式）
        GenericJackson2JsonRedisSerializer valueSerializer = new GenericJackson2JsonRedisSerializer();

        // 构建 Redis 缓存配置（可自定义过期时间、前缀等）
        RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                // 默认缓存过期时间 30 分钟
                .entryTtl(Duration.ofMinutes(30))
                // 缓存键前缀（如 "cache:userCache::1"）
                .prefixCacheNameWith("cache:")
                // 键序列化
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer))
                // 值序列化
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer))
                // 不缓存 null 值（避免缓存穿透）
                .disableCachingNullValues();

        // 构建 RedisCacheManager（绑定 Redis 连接工厂）
        return RedisCacheManager.builder(connectionFactory)
                // 应用默认配置
                .cacheDefaults(cacheConfig)
                .withCacheConfiguration("userCache", RedisCacheConfiguration.defaultCacheConfig()
                        // 单独为 "userCache" 配置过期时间
                        .entryTtl(Duration.ofHours(1)))
                .build();
    }
}